package service

import (
	"github.com/smallnest/weighted"
	"github.com/wonderivan/logger"
	"net/http"
	"time"
	"ucenter/app"
	dao2 "ucenter/app/dao"
)

var (
	Svc Service
)

type PayToken struct {
	AppId          string `json:"app_id"`
	AppOrderId     int64  `json:"order_id"`
	Channel        string `json:"channel"`
	PaymentOrderId string `json:"payment_order_id"`
	Attachment     string `json:"attachment"`
	TransactionNo  string `json:"order_id"`
	Payload        []byte `json:"payload"`
}

type Connector struct {
	Host   string `yaml:"host" json:"host"`
	Port   int    `yaml:"port" json:"port"`
	Weight int    `yaml:"weight" json:"-"`
}
type Service interface {
	//Connector provider a connector by weight use round-robin
	Connector() (*Connector, error)
	//ConnectorWatcher witch watch node list file modify
	ConnectorWatcher() error
	//PreOrder rummy client get pay token
	PreOrder(uid int64, payChannel string, channelId string, tradeType TradeType, amount int, appId string) (payToken *PayToken, err error)
	//UpdateOrderStatus update order status
	UpdateOrderStatus(orderId int64, status string) (err error)
}

type service struct {
	rummyNodeList *weighted.SW
	conf          *app.AppConf
	payClient     *http.Client
	uuidClient    *http.Client
	dao           *dao2.Dao
}

func NewService(conf *app.AppConf) Service {
	Svc = &service{
		rummyNodeList: &weighted.SW{},
		conf:          conf,
		payClient:     newPayClient(conf.PayConf),
		uuidClient:    newUUIDClient(conf.UUIDConf),
		dao:           dao2.New(conf.Mysql, conf.Redis),
	}
	err := Svc.ConnectorWatcher()
	if err != nil {
		logger.Error("rummy connector fail, %s", err.Error())
	}

	return Svc
}

func newPayClient(conf *app.HttpClient) *http.Client {
	if conf == nil || conf.Host == "" {
		logger.Warn("pay client init fail, no config")
		return nil
	}
	return &http.Client{
		Transport: &http.Transport{
			MaxIdleConns:    conf.MaxIdleConn,
			MaxConnsPerHost: conf.MaxConnPerHost,
			IdleConnTimeout: time.Duration(conf.IdleConnTimeout),
		},
		Timeout: time.Duration(conf.Timeout),
	}
}
func newUUIDClient(conf *app.HttpClient) *http.Client {
	if conf == nil {
		logger.Warn("uuid client init fail, no config")
		return nil
	}
	return &http.Client{
		Transport: &http.Transport{
			MaxIdleConns:    conf.MaxIdleConn,
			MaxConnsPerHost: conf.MaxConnPerHost,
			IdleConnTimeout: time.Duration(conf.IdleConnTimeout),
		},
		Timeout: time.Duration(conf.Timeout),
	}
}
